package ar.uba.fi.tonyvaliente.commands;

import java.util.ArrayList;
import java.util.List;

import ar.uba.fi.tonyvaliente.signature.HashFunction;
import ar.uba.fi.tonyvaliente.signature.SignatureConfiguration;
import ar.uba.fi.tonyvaliente.signature.SignatureConfigurationException;
import ar.uba.fi.tonyvaliente.signature.process.CreateSignatureResult;
import ar.uba.fi.tonyvaliente.signature.process.SignatureGenerator;
import ar.uba.fi.tonyvaliente.utils.RecursosAplicacion;

public class CreateSignatureCommand extends Command {

	private boolean recognized;
	private String configurationPath;
	private String documentPath;
	private List<HashFunction> hashFunctions;
	private int length;

	public CreateSignatureCommand(String[] args) {
		super(args);

		recognized = false;
		configurationPath = "";

		if (args.length > 0) {
			String command = args[0];
			command = command.toLowerCase();
			if (command.equals("-createsignature")) {
				recognized = true;
				if (args.length > 1) {
					configurationPath = RecursosAplicacion.instance().getProperty("hash.config");
					documentPath = args[1];
				}
			}
		}
	}

	private CommandResult createSignature() {
		SignatureConfiguration config = null;
		try {
			config = SignatureConfiguration.loadFromFile(configurationPath);
		} catch (SignatureConfigurationException e) {
			e.printStackTrace();
			return new CommandResult(true, false, e.getMessage());
		}
		hashFunctions = new ArrayList<HashFunction>(config.getHashFunctions());
		length = config.getSignatureLength();
		
		CreateSignatureResult createSignatureResult = SignatureGenerator.process(documentPath, hashFunctions, length);
		if (createSignatureResult.isSuccess()){
			return CommandResult.EXECUTE_SUCCESSFULLY;
		}else{
			return new CommandResult(true, false, createSignatureResult
					.getErrorMessage());
		}
	}

	public CommandResult execute() {
		if (!recognized)
			return CommandResult.NOT_RECOGNIZED;

		if (configurationPath == null || documentPath == null)
			return new CommandResult(true, false, "Invalid parameters");

		return createSignature();
	}

	public String getSignature() {
		return "-createSignature \"config path\" \"documentPath\" ";
	}

	public String getDescription() {
		return "Creates a signature for the specified document using the config file and adds it to the signature file";
	}

	public String[] getExamples() {
		return new String[] { "-createSignature \"/var/local/config/config.properties\" \"/var/local/documents/doc.html\"" };
	}
}
